﻿//CommissionRegistry.cs
//Copyright (c) 2013 StockSharp LLC, all rights reserved.
//This code module is part of StockSharp library.
//This code is licensed under the GNU GENERAL PUBLIC LICENSE Version 3.
//See the file License.txt for the license details.
//More info on: http://stocksharp.com

namespace StockSharp.Algo.Commissions
{
	using System;
	using System.Collections.Generic;
	using System.ServiceModel;

	using Ecng.Collections;
	using Ecng.Common;
	using Ecng.Net;

	/// <summary>
	/// Реестр всех доступных тарифных планов, получающий данные с сервера StockSharp.
	/// </summary>
	public sealed class CommissionRegistry
	{
		private readonly Lazy<ChannelFactory<ICommissionService>> _factory;
		private readonly SynchronizedDictionary<string, CommissionRule[]> _profiles = new SynchronizedDictionary<string, CommissionRule[]>();

		/// <summary>
		/// Создать <see cref="CommissionRegistry"/>.
		/// </summary>
		public CommissionRegistry()
			: this("http://stocksharp.com/services/commissionservice.svc".To<Uri>())
		{
		}

		/// <summary>
		/// Создать <see cref="CommissionRegistry"/>.
		/// </summary>
		/// <param name="address">Адрес сервера.</param>
		public CommissionRegistry(Uri address)
		{
			if (address == null)
				throw new ArgumentNullException("address");

			_factory = new Lazy<ChannelFactory<ICommissionService>>(() => ChannelHelper.Create("commission", () => new ChannelFactory<ICommissionService>(new WSHttpBinding(), new EndpointAddress(address))));
		}

		private string[] _names;

		/// <summary>
		/// Все названия тарифных планов.
		/// </summary>
		public IEnumerable<string> Names
		{
			get { return _names ?? (_names = _factory.Value.Invoke(s => s.GetNames(ServerCredentials.Instance.Login, ServerCredentials.Instance.Password))); }
		}

		/// <summary>
		/// Получить тарифный план по его имени.
		/// </summary>
		/// <param name="name">Название тарифного плана.</param>
		/// <returns>Тарифный план.</returns>
		public CommissionRule[] Get(string name)
		{
			return _profiles.SafeAdd(name, key => _factory.Value.Invoke(s => s.GetRules(ServerCredentials.Instance.Login, ServerCredentials.Instance.Password, key)));
		}
	}
}